<template>
  <div :style="{ height: lastHeight + 'px'}">
    <div style=" display: flex;align-items: center; height: 42px;margin-left: 5px;">
      <el-button v-if="tabs.type==='flow'" @click="runProcess()" type="text" size="mini">
                <span v-if="runProcesstag"><svg-icon icon-class="play-circle" />
                 运行</span>
        <span v-if="stopProcesstag"><svg-icon icon-class="stop-circle" />
                 停止</span>
      </el-button>
      <el-button @click="saveflow()" type="text" size="mini">
        <svg-icon style="font-size: 16px" icon-class="folder-add" />
        保存
      </el-button>
      <el-button @click="showlog()" v-if="tabs.type==='flow'" type="text" size="mini">
        <svg-icon style="font-size: 16px" icon-class="catalogue" />
        查看日志
      </el-button>
      <el-button @click="openNode()" v-if="tabs.type==='flow'" type="text" size="mini">
        <svg-icon style="font-size: 16px" icon-class="lock-off" />
        启用
      </el-button>
      <el-button @click="offNode()" v-if="tabs.type==='flow'" type="text" size="mini">
        <svg-icon style="font-size: 16px" icon-class="lock-on" />
        停用
      </el-button>
    </div>
    <graphContainers ref="content" :flowName="tabs.flowName" :flowId="tabs.flowId"></graphContainers>
    <!--    <div class="showLogButton" @click="showlog()">-->
    <!--      <svg-icon style="font-size: 19px;" icon-class="caret-up-small"/>-->
    <!--    </div>-->
    <el-dialog top="140px" @close="isLogShow=false" class="logDialog" width="90%" title="执行日志"
               style="z-index:1000000;margin-top: -50px"
               :close-on-click-modal=false :visible.sync="isLogShow">
      <div :style="{ height: lastHeight-230 + 'px'}" style="overflow: auto">
        <!--        <span style="color: #fff" v-html="log"></span>-->
        <el-input type="textarea" :rows="30" readonly v-model="log"></el-input>
      </div>


    </el-dialog>
    <!--    <transition name="el-zoom-in-bottom">-->
    <!--      <div v-show="isLogShow" class='logStyle' >-->
    <!--        <div class="closeButton" @click="closeLog">-->
    <!--          <svg-icon style="font-size: 19px;" icon-class="caret-down-small"/>-->
    <!--        </div>-->
    <!--        <span style="color: #fff" v-html="log"></span>-->
    <!--      </div>-->
    <!--    </transition>-->
  </div>
</template>
<script>
import graphContainers from "./graphContainers.vue";

export default {
  // mixins: [autoResize],
  components: { graphContainers },
  props: ["tabs", "flowName"],
  data() {
    return {
      runProcesstag: true,
      stopProcesstag: false,
      execId: "",
      isLogShow: false,
      log: "",
      intervalId: "",
      triggerDate: "",
      enable: true,
      openTag: false,
      overtag:false
    };
  },
  methods: {
    //处理节点
    handlenode() {
      let components = []; //节点数组
      let querydata = {
        componentSeq: "",//节点id
        componentType: "",//节点类型
        px: "",
        py: "",
        name: ""
      };
      const { nodes, edges } = this.$refs.content.getNodeEdge();
      // console.log(nodes,111)
      nodes.forEach((item) => {
        let idTga = false;
        querydata.enable = true;
        querydata.componentSeq = item.id;
        querydata.componentType = item.store.data.data.nodetype;
        querydata.px = item.store.data.position.x;
        querydata.py = item.store.data.position.y;
        querydata.name = item.store.data.attrs.label.text;
        if (this.selectNodes) {
          this.selectNodes.forEach((snode) => {
            if (snode.id === item.id) {
              idTga = true;
              querydata.enable = this.enable;
            }
          });
        }
        if (!idTga) {
          querydata.enable = item.data.nodeopen;
        }
        if (querydata.enable === "") {
          querydata.enable = true;
        }
        console.log(querydata, 111);
        components.push({ ...querydata });
      });
      // console.log(components,'节点数据')
      return components;
    },
    //处理线
    handledges() {
      let components = []; //线数组
      let querydata = {
        seq: "",
        cmpFrom: "",//id
        cmpTo: "",
        portFrom: "",
        portTo: "",
        text: ""
      };
      const { nodes, edges } = this.$refs.content.getNodeEdge();
      // console.log(edges,'需要渲染的线')
      edges.forEach((item) => {
        item.sourceNode.port.ports.forEach((portitem) => {
          if (portitem.id === item.store.data.source.port) {
            querydata.portFrom = portitem.group;
          }
        });
        item.targetNode.port.ports.forEach((portitem) => {
          if (portitem.id === item.store.data.target.port) {
            // console.log(item.store.data.source.port)
            querydata.portTo = portitem.group;
          }
        });
          querydata.seq = item.id,
          querydata.cmpFrom = item.sourceNode.id,
          querydata.cmpTo = item.targetNode.id,
          querydata.text =item.store.data.labels?item.store.data.labels[0].attrs.text.text:''
          components.push({ ...querydata });
      });
      // console.log(components,'线数据')
      return components;

    },
    //保存流程节点
    //runtag用来判断是否为运行调用的保存
    saveflow(runtag) {
      const querydata = {
        id: this.tabs.flowId,//流程id
        components: this.handlenode(),
        relations: this.handledges()
      };
      // console.log(querydata,'前端数据')
      return this.$http.post("/flow/saveFlow", querydata).then((res) => {
        // console.log(res)
        if (res.code === "200" && !runtag) {
          this.$message.success("保存成功");
          this.$bus.$emit("getTreeData");
        }
        if (res.code === "200" && runtag === "open") {
          this.$message.success("启用成功");
        }
        if (res.code === "200" && runtag === "off") {
          this.$message.success("停用成功");
        }
        if (res.code !== "200" && (runtag !== "run" || runtag === "open" || runtag === "off")) {
          this.$message({
            showClose:true,
            type: "error",
            message: `${res.msg}`
          });
          // this.$message.error(`${res.msg}`);
        }
      }).finally(() => {
        console.log(this.handlenode());
        this.$refs.content.setNodestuts(this.handlenode(), "openTag");
      });
    },
    async runProcess() {
      //运行流程
      if (this.runProcesstag) {
        this.overtag = false
        this.execId = "";
        //将所有节点状态置为start
        const { nodes, edges } = this.$refs.content.getNodeEdge();
        const nodearry = {};
        nodes.forEach((node) => {
          nodearry[node.id] = "start";
        });
        this.$refs.content.setNodestuts(nodearry);
        await this.saveflow("run");
        this.$http.post("/executor/start", {
          objType:'1',
          objId:this.tabs.flowId,
          // flowId: this.tabs.flowId,
          reload: true
        }).then((res) => {
          // console.log(res)
          this.runProcesstag = false;
          this.stopProcesstag = true;
          this.$message.success("启动成功");
          this.execId = res.data.execId;
          this.server = res.data.server;
          this.flowId = res.data.flowId;
          this.triggerTime = res.data.triggerTime;
          this.triggerDate = res.data.triggerDate;
          this.intervalId = setInterval(this.getlog, 1000);
        }).catch(() => {
          this.runProcesstag = false;
          this.runProcesstag ? (this.runProcesstag = false, this.stopProcesstag = true) : (this.runProcesstag = true, this.stopProcesstag = false);
          this.$message({
            showClose:true,
            type: "error",
            message: `${res.msg}`
          });
          // this.$message.error(`${res.msg}`);
        })
          .finally(() => {

          });
      }
      //停止流程
      else {
        //设置当前节点的状态为失败
        const { nodes, edges } = this.$refs.content.getNodeEdge();
        const nodearry = {};
        nodes.forEach((node) => {
          if (node.store.data.data.nodestatus === "begin") {
            nodearry[node.id] = "error";
          } else {
            nodearry[node.id] = node.store.data.data.nodestatus;
          }
        });
        this.$refs.content.setNodestuts(nodearry);
        let querydata = {
          execId: this.execId,
          triggerDate: this.triggerDate,
          server: this.server,
          flowId: this.flowId,
          triggerTime: this.triggerTime
        };
        this.$http.post("/executor/stop", querydata).then((res) => {
          // console.log(res)
          if (res.code === "200") {
            this.$message.success("停止成功");
          } else {
            this.$message({
              showClose:true,
              type: "error",
              message: `${res.msg}`
            });
            // this.$message.error(`${res.msg}`);
          }
        });
      }

    },
    getlog() {
      let querydata = {
        execId: this.execId,
        triggerDate: this.triggerDate,
        reload: true,
        server: this.server,
        flowId: this.flowId,
        triggerTime: this.triggerTime
      };
      this.$http.post("/executor/getLog", querydata).then((res) => {
        // console.log(res)
        if (res.data.nodes) {
          this.$refs.content.setNodestuts(res.data.nodes);
        }
        // this.log = res.data.msg.replace(/\n/g, "<br>");
        this.log = res.data.msg;
        if (res.data.status === "flowover") {
          //只在第一次执行结束时提示
          if(!this.overtag){
            this.$message.success("执行结束");
          }
          this.overtag = true
          setTimeout(() => {
            // 这里放置要延迟执行的代码
            this.runProcesstag ? (this.runProcesstag = false, this.stopProcesstag = true) : (this.runProcesstag = true, this.stopProcesstag = false);
            this.runProcesstag = true;
            this.stopProcesstag = false;
            clearInterval(this.intervalId);
          }, 3000);
        }
      });
    },
    showlog() {
      this.isLogShow = true;
    },
    openNode() {
      //获取选中元素
      this.selectNodes = this.$refs.content.graph.getSelectedCells();
      if (this.selectNodes.length > 0) {
        this.enable = true;
        this.openTag = true;
        this.saveflow("open");
      } else {
        this.$message.warning("请选择节点");
      }
      // console.log(this.selectNodes);
    },
    offNode() {
      //获取选中元素
      this.selectNodes = this.$refs.content.graph.getSelectedCells();
      if (this.selectNodes.length > 0) {
        this.enable = false;
        this.openTag = true;
        this.saveflow("off");
      } else {
        this.$message.warning("请选择节点");
      }
      // console.log(this.selectNodes);
    },
    closeLog() {
      this.isLogShow = false;
    }
  },
  computed: {
    documentHeight() {
      return this.$store.getters.documentHeight;
    },
    lastHeight() {
      return this.documentHeight - 90;
    }
  },
  mounted() {

  }
};
</script>
<style>
body {
    position: fixed;
    top: 0px;
    left: 0px;
    overflow: hidden;
    transform-origin: left top;
    z-index: 999;
    margin: 0;
}

.logStyle {
    overflow: auto;
    z-index: 2001;
    width: 100%;
    height: 200px;
    background-color: #27292c;
    position: absolute;
    bottom: 0;
}

.closeButton {
    float: right;
    /*color: #454857;*/
    color: #fff;
}

.showLogButton {
    color: #fff;
    z-index: 2000;
    position: fixed;
    bottom: 0;
    right: 6px;
}

</style>
